from django.shortcuts import render
from django.shortcuts import HttpResponse
import json
from db.mydb import MyDBConnection
from db.dao.broker import Broker
from db.utils.dfutils import load_json_to_object
def broker_index(request):
    current = 1#如果用户不提供，默认看第一页
    pagesize = 10#如果用户不提供，默认每页5条
    if request.method == 'GET':  #大小写
        myDBConnection = MyDBConnection()
        current = request.GET.get("current")
        pagesize = request.GET.get("pagesize")
        print(f'1111 {request.GET.get("current")}')
        offset = (int(current) - 1) * int(pagesize) #计算每页的第一条编号
        brokers_json = myDBConnection.fetch_data_by_sql(f"select * from broker limit {offset},{pagesize}")
        msg = f'现在查看的是第{current}页，每页大小{pagesize}'
        print(brokers_json)
        code = 200
        rep_json =  {"code":code,"msg":msg,"brokers":brokers_json}
    if bool(request.GET.get('json'))==True:
        return HttpResponse(json.dumps(rep_json), content_type="application/json")
    else:
        return render(request, "broker/index.html", rep_json)

def broker_add(request):
    # p_id = request.POST.get("p_id")
    # p_name = request.POST.get("p_name")
    data = request.body.decode("utf-8")
    print(type(data))
    myDBConnection =MyDBConnection()
    broker_json_obj = json.loads(data)
    print(broker_json_obj)
    broker = load_json_to_object(broker_json_obj,broker())
    print(type(broker))
    myDBConnection.insert_entity(broker)
    pname = broker.p_name
    print(pname)
    msg = f"{pname}球员添加成功"
    code = 200
    rep_json = {"code":code,"msg":msg}
    return HttpResponse(json.dumps(rep_json), content_type="application/json")